<template>
    <div class="cont">
        <nav-bar textColor="#333333" rightImg="https://h5.dhcc.wang/newprogram/wxRobot/nav_refresh_black.png" rightText="同步"
            title="新增发单群" bgStyle="#fff" :rotate.sync="reload" @leftClick="back" @rightClick="refresh" />
        <div class="cont-main">
            <div class="list p-b-50">
                <div class="m-t-10 p-lr-12 m-lr-10 bg-white radius8 box-shadow">
                    <div class="p-lr-12 p-t-15">
                        <img class="list-top" src="https://img.huajuanyun.com/utools/2024/1127/1732673913269.png" alt="">
                    </div>
                    <div class="color-9 font-11 p-tb-8">如果已满足条件仍无法显示群，可在群里发送任意消息后重新同步等待几分钟后重试；仍无法显示，请次日重新尝试</div>
                </div>
                <!-- <div class="tab-box font-13">
                    <div>① 群人数必须<b>大于3人</b>，并且群<b>保存到通讯录</b>中；</div>
                    <div class="m-t-5">② 点击右上方↗同步按钮，系统会自动同步群通讯录，如果未同步，等待几分钟后再刷新即可；</div>
                    <div class="m-t-5">③ 如遇仍旧获取不到群，请<b>在群里发送一条消息后</b>，重复第2步操作即可。</div>
                    <div class="m-t-5">④ 以上步骤仍获取不到群，请次日重新第2步操作</div>
                </div> -->
                <van-list v-if="list && list.length > 0" :finished="finished" :immediate-check="false" finished-text=""
                    @load="onLoad">
                    <div class="list-cont m-15">
                        <div class="flex justify-between align-center  text-center m-b-5">
                            <div class="list-top__title font-16 text-bold">
                                选择发单群
                            </div>
                            <!-- <div class="font-12 color-9" v-if="type !== 'user'" @click="handleQuestion">为什么没有我的群？</div> -->
                        </div>
                        <div class="p-b-10 color-9 font-12" v-if="total">已同步到 <span class="color-red">{{ total }}
                            </span>个群，选择需要的群添加到发单群即可</div>
                        <template>
                            <van-radio-group v-model="checked" icon-size="18">
                                <van-cell-group :border="false" style="background: none;">
                                    <van-cell v-for="(item, index) in list" :key="index" clickable
                                        @click="checked = item.user_name; checkedIndex = index"
                                        :class="checked == item.user_name ? 'm-b-10 radius4 checked' : 'm-b-10 radius8 '">
                                        <template #title>
                                            <div class="list-item flex align-center">
                                                <img class="m-r-10 radius4" width="48"
                                                    :src="item.small_head_img_url || 'https://h5.dhcc.wang/images/default_avatar.png'"
                                                    alt="">
                                                <div class="title flex align-center">
                                                    {{ item.nick_name }}
                                                </div>
                                            </div>
                                        </template>
                                        <template #right-icon>
                                            <div class="flex align-center">
                                                <van-icon name="delete" color="#ee0a24" v-if="showDel" @click.stop="handleDel(item, index)"></van-icon>
                                                <van-radio :name="item.user_name" class="m-l-10" />
                                            </div>
                                            
                                        </template>
                                    </van-cell>
                                </van-cell-group>
                            </van-radio-group>
                        </template>
                    </div>
                    <div class="m-lr-12">
                        <div class="color-9 font-12 m-b-5">注：如果上方出现已解散的群或已退出的群，可点击下方按钮彻底移除对应的群，系统将不再展示。</div>
                        <span @click="showDel = !showDel" class="opt-btn font-12">{{showDel ? '取消' : '点我'}}操作</span>
                    </div>
                </van-list>
                <noData v-else marginTop="50px" text="暂无微信群" />
            </div>
            <div @click="confrim" class="bottom-btn"
                :style="checked ? { background: bgStyle, backgroundSize: '100%' } : 'background: #dddddd;color:#fff'">添加到发单群
            </div>
        </div>
        <custom-popup v-if="showPopup" :popup-visible.sync="showPopup" :type="popupType" :scan-info="scanInfo"
            :groupInfo="list[checkedIndex]" @close="closePopup" />
    </div>
</template>

<script>
import { List, Cell, CellGroup, RadioGroup, Radio } from 'vant'
import CustomPopup from '@/components/CustomPopup.vue'
export default {
    components: {
        CustomPopup,
        [List.name]: List,
        [Cell.name]: Cell,
        [CellGroup.name]: CellGroup,
        [RadioGroup.name]: RadioGroup,
        [Radio.name]: Radio
    },
    data() {
        return {
            config: {},
            main_color: '',
            assist_color: '',
            params: {},
            bgStyle: '',
            reload: false,
            checked: '',
            checkedIndex: 0,
            loading: false,
            finished: false,
            nodata: false,
            nomore: false,
            checkedList: [],
            list: [],
            total: '',
            tabIndex: 0,
            page: 1,
            pagesize: 20,
            showPopup: false,
            popupType: 12,
            scanInfo: {},
            showDel: false

        }
    },
    created() {
        this.setHeader()
    },
    mounted() {
        this.config = this.$DB.get('robotCfg')
        this.bgStyle = `linear-gradient(90deg, ${this.config.mac_main_color} 0%, ${this.config.mac_assist_color} 100%)`
        this.getList(true)
    },
    // activated () {
    //     this.tabIndex = 0
    //     const options = this.$route.query
    //     this.params = JSON.parse(options.params)

    //     this.checked = ''
    //     this.getList(true)
    //     this.setHeader()
    // },
    methods: {
        setHeader() {
            this.$common.setHeader({
                native_headershow: 0,
                topstyle: 'topcolor',
                native_top_words_color: '#ffffff',
                str_link_color: '#ffffff',
                end_link_color: '#ffffff'
            })
        },
        getList(loading) {
            const _this = this
            if (this.tabIndex == 1) {
                setTimeout(() => {
                    this.reload = false
                }, 300)
                return
            }
            if (loading) {
                this.page = 1
                this.list = []
                this.checked = ''
            }
            this.$api.getListGroup({ status: -1, page: this.page, pagesize: this.pagesize }, loading).then(async res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.total = res.data.total
                this.list = [...this.list, ...res.data.list]
                this.page++
                this.loading = false
                if (this.list.length == res.data.total) {
                    this.finished = true
                }
            }).finally(() => {
                setTimeout(() => {
                    this.reload = false
                }, 300)
            })
        },
        async confrim() {
            if (!this.checked) {
                return this.$toast('请选择发单群')
            }
            let isBeian = await this.taobaoBa(1);
            if (!isBeian) return;
            let pddBeian = await this.goBeian(4)
            if (!pddBeian) return;
            this.$api.updateGroup({
                group_type: 2,
                username: this.checked
            }).then(res => {
                if (res.code == 1) {
                    this.$toast('保存成功')
                    this.back()
                } else {
                    if (res.data && res.data.wechat_info && res.data.wechat_info.user_name) {
                        this.showPopup = true
                        this.scanInfo = res.data.wechat_info
                    } else {
                        this.$toast(res.msg)
                    }
                }
            })
        },
        goBeian(num) {
            return new Promise((resolve, reject) => {
                this.$api.checkBeian({ union_type: num }).then(res => {
                    if (res.data.need_beian == 1) {
                        this.pddBeiAn(res.data.beian_urls.short_url, num)
                        resolve(false)
                    } else {
                        resolve(true)
                    }
                })

            })
        },
        taobaoBa(num) {
            return new Promise((resolve, reject) => {
                this.DS.call('DS.checkBeian', num, (v) => {
                    resolve(true)
                })
            })

        },
        refresh() {
            this.reload = true
            // 同步联系人
            this.$api.syncContact({}).then(async res => {
                if (res.code != 1) {
                    return this.$toast(res.msg)
                }
                this.getList(true)
            }).finally(() => {
            })
        },
        onLoad() {
            if (!this.finished && !this.loading) {
                this.loading = true
                this.getList()
            }
        },
        tabChange(index) {
            if (index == this.tabIndex) return
            this.tabIndex = index
            this.tabIndex == 0 ? this.getList(true) : this.list = []
        },
        back() {
            this.$router.go(-1)
        },
        pddBeiAn(url, type) {
            this.$dialog.confirm({
                title: '温馨提示',
                message: type == 4 ? '当前账号未进行拼多多授权，请先进行授权备案！' : '当前账号未进行淘宝授权，请先进行授权备案！'
            }).then(() => {
                this.DS.call('DS.openBuyLink', {
                    type,
                    url
                })
            }).catch(() => {
                // cancel
            })
        },
        setHeader() {
            this.$common.setHeader({
                native_headershow: 0,
                topstyle: 'topcolor',
                native_top_words_color: '#ffffff',
                str_link_color: '#ffffff',
                end_link_color: '#ffffff'
            })
        },
        closePopup() {
            this.showPopup = false
        },
        // 删除群
        handleDel (item, index) {
            this.$dialog.confirm({
                title: '温馨提示',
                message: '确定从列表中删除该群？'
            }).then(() => {
                this.$api.deleteGroup({
                    username: item.user_name
                }).then(res => {
                    this.$toast('删除成功')
                    this.checked = ''
                    this.list.splice(index, 1)
                })
            }).catch(() => {
                // cancel
            })
        }
    }
}
</script>
<style lang="less" scoped>
.cont {
    font-size: 14px;
    padding-top: 46px;

    &-main {
        /deep/ .van-cell__title {
            max-width: calc(100% - 18px);
        }

        // padding: 12px 12px 52px;
        .list {
            margin-bottom: 18px;
            &-top {
                width: 100%;
            }

            &-title {
                position: relative;
                padding-left: 10px;
                margin-bottom: 20px;

                i {
                    content: '';
                    position: absolute;
                    left: 0;
                    width: 2px;
                    height: 12px;
                    border-radius: 1px;
                }
            }

            &-cont {
                .list-top__title {
                    position: relative;
                    &:after {
                        content: '';
                        position: absolute;
                        width: 16px;
                        height: 16px;
                        bottom: -2px;
                        right: -6px;
                        background: rgba(137,153,241,.3);
                        border-radius: 50%;
                    }
                }
                .list-item {
                    .title {
                        .group-name {
                            max-width: 65%;

                            img {
                                width: 18px;
                                height: 18px;
                                margin-right: 5px;
                            }
                        }

                        &-tag {
                            height: 18px;
                            line-height: 18px;
                            margin-left: 15px;
                            padding: 0 5px;
                            border: 1px solid transparent;
                            border-radius: 4px;
                            font-size: 11px;
                        }
                    }
                }

                /deep/ .van-cell {
                    padding: 10px 12px;

                    &::after {
                        left: 0;
                        right: 0;
                    }
                }

                .nodata {
                    height: 400px;

                    img {
                        width: 255px;
                    }
                }

                .btn-add {
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 143px;
                    margin: 15px auto 0;
                    padding: 9px 0;
                    line-height: 20px;
                    color: #666;
                    border: 1px solid #ccc;
                    border-radius: 4px;
                }
            }

            .tab-box {
                background: linear-gradient(180deg, #ffffff, #fffbe8 100%);
                color: #f24100;
                padding: 15px 15px 10px;
            }
        }
        .opt-btn {
            padding: 0 5px;
            color: #f24100;
            border: 1px solid #f24100;
            border-radius: 10px;
        }

        .checked {
            .list-cont {
                padding: 10px 12px 1px;
            }

            .group-name {
                max-width: 70%;
            }
        }

        .bottom-btn {
            position: fixed;
            bottom: 20px;
            left: 0;
            right: 0;
            margin: 0 auto;
            width: 90%;
            padding: 10px 0;
            color: #fff;
            border-radius: 100px;
            font-size: 16px;
            text-align: center;
            font-weight: bold;
        }
    }
}

.checked {
    background: #bedcf9;
}
</style>